package com.wly.datapool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.mina.core.session.IoSession;

import com.google.protobuf.Message;
import com.wly.datapool.playerpool.BasePlayer;
import com.wly.define.SessionAttributeDefine;
import com.wly.gpb.Login.LogIn;

public class SessionManager
{
	static private HashMap<Integer, IoSession> _sessionArr;
	static private SessionManager _instance;
	
	private SessionManager()
	{
		_sessionArr = new HashMap<Integer, IoSession>();
	}
	
	static public SessionManager getInstance()
	{
		if(_instance == null)
		{
			_instance = new SessionManager();
		}
		return _instance;
	}
	
	public void addSession(IoSession session)
	{
		BasePlayer player;
		player = (BasePlayer) session.getAttribute(SessionAttributeDefine.PLAYER);
		if(player != null)
		{
			_sessionArr.put(player.getPlayerId(), session);
		}
	}
	
	public void removeSession(IoSession session)
	{
		BasePlayer player;
		player = (BasePlayer) session.getAttribute(SessionAttributeDefine.PLAYER);
		if(player != null)
		{
			player.onLeave();
			_sessionArr.remove(player.getPlayerId());
		}
	}
	
	public void broadcastOnlineMessage(IoSession session, Message msg)
	{
		Iterator it = _sessionArr.values().iterator();
		IoSession sessionTmp;
		while(it.hasNext())
		{
			sessionTmp = (IoSession)it.next();
			sessionTmp.write(msg);
		}
	}
	
	public void sendMessageToPlayer(IoSession session,BasePlayer player, Message msg)
	{ 
		IoSession targetSession;
		targetSession = (IoSession)_sessionArr.get(player.getPlayerId());
		if(targetSession != null)
		{
			targetSession.write(msg);
		}
	}
}
